package com.dingwen.treasure.mybatisplus.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dingwen.treasure.base.enums.ActivityStatusEnum;
import com.dingwen.treasure.model.entity.ActivityInfo;
import com.dingwen.treasure.mybatisplus.service.ActivityInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 　ActivityInfoServiceImpl
 * 　@author dingwen
 * 　@date 2022/5/14$
 */
@Service
@Slf4j
public class ActivityInfoServiceImpl implements ActivityInfoService {

    /**
     * 按id查找
     *
     * @param activityId 活动id
     * @return {@link Optional}<{@link ActivityInfo}>
     */
    @Override
    public Optional<ActivityInfo> findById(Long activityId) {
        // 模拟查询数据库，获取当前活动状态
        ActivityInfo activityInfo = ActivityInfo.builder().id(activityId).status(ActivityStatusEnum.EDITING).build();
        return Optional.ofNullable(activityInfo);
    }

    /**
     * 改变状态
     *
     * @param beforeStatus 变更前状态
     * @param afterStatus  变更后状态
     * @param activityId   活动id
     * @return {@link Boolean}
     */
    @Override
    public synchronized Boolean changeStatus(ActivityStatusEnum beforeStatus, ActivityStatusEnum afterStatus, Long activityId) {
        // 查询数据库活动信息
        Optional<ActivityInfo> activityInfoOptional = findById(activityId);

        activityInfoOptional.orElseThrow(() -> {
            String message = "activityId:{},不存在";
            return new RuntimeException(StrUtil.format(message, activityId));
        });

        if (!beforeStatus.equals(activityInfoOptional.get().getStatus())) {
            return false;
        }

        // 更新数据库
        log.info("活动状态变更成功，已更新到数据库");
        return true;
    }
}
